package com.app.micaihu.view.main.game.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;

import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.bean.game.GameContent;
import com.app.micaihu.bean.game.GameRaidersEntity;
import com.app.micaihu.bean.game.GameRelated;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.custom.components.downandupload.LoadingView;
import com.app.micaihu.custom.view.RatingBarView;
import com.app.micaihu.custom.view.listivew.ExpandListview;
import com.app.micaihu.custom.view.web.CustomWebView;
import com.app.micaihu.utils.ImageLoadUtils;
import com.app.micaihu.videoplayer.JCVideoPlayerGame;
import com.app.micaihu.view.main.game.GameCommentActivity;
import com.app.micaihu.view.main.game.GameDetailActivity;
import com.app.micaihu.view.main.game.GameRaidersListActivity;
import com.app.micaihu.view.main.game.GameRaidersNewsActivity;
import com.app.micaihu.view.main.game.GameRaidersVideoActivity;
import com.app.micaihu.view.main.game.GameScoreActivity;
import com.app.micaihu.view.main.game.adapter.GameRaidersAdapter;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ViewSizeUtils;
import com.blankj.utilcode.util.ClipboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.util.List;


/**
 * Created by Guo on 2017/3/9.
 * <p>
 * 游戏的详情
 */

public class GameDescView extends NestedScrollView implements View.OnClickListener {

    JCVideoPlayerGame jcVideoplayer;
    TextView tvGameName;
    TextView tvGameInfo1;
    TextView tvGameInfo2;
    TextView tvGameInfo3;
    TextView tvGameType1, tvGameType2, tvGameType3;
    //    @Bind(R.id.tv_game_info3)
//    TextView tvGameInfo3;
    TextView tvGameScore;
    RatingBarView rbGameScore;
    TextView tvDownCount;
    LoadingView btnOpration;

    RatingBarView rbCommentScroe;
    TextView tvGoComment;

    LinearLayout btnComment;

    TextView tvEditorRecommend;//小编的 简介

    CustomWebView cwvContentWebview;//简介的webview

//    @Bind(R.id.btn_show_all_content)
//    LinearLayout btnShowAllContent;//简介的展开全部

    TextView tvExpends;
    //游戏的相关攻略
    ExpandListview elvAboutStrategy;
    LinearLayout ll_about_strategy;

    LinearLayout llAboutGameContainer;//相关游戏.


    LinearLayout lRelatedContainer;//相关游戏的容器

    LinearLayout llVideoContentContainer;//viode内容简介的 部分

    LinearLayout llEditorContainer;//小编推荐模块 部分

    TextView editorName;//编辑的名字

    LinearLayout llScroe;//评分模块

    LinearLayout infoContainer;
    FrameLayout playerContainer;
    ImageView ivAppIcon;
    private boolean isExpended;


    public JCVideoPlayerGame getJcVideoplayer() {
        return jcVideoplayer;
    }


    public CustomWebView getCwvContentWebview() {
        return cwvContentWebview;
    }

    private Context context;
    private float webviewY;
    private GameContent mGameContent;
    private Activity activity;

    public static final String IMAGE_URL = "image_url";
    private OnViewScrollListener mOnViewScrollListener;

    public GameDescView(Context context) {
        super(context);
        this.context = context;
    }

    public GameDescView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    public GameDescView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
    }

    public void initView() {
        inflate(this.context, R.layout.view_gamestretegy, this);
        ivAppIcon = findViewById(R.id.ivAppIcon);
        ll_about_strategy = findViewById(R.id.ll_about_strategy);
        jcVideoplayer = findViewById(R.id.jc_videoplayer);
        tvGameName = findViewById(R.id.tv_game_name);
        tvGameInfo1 = findViewById(R.id.tv_game_info1);
        tvGameType1 = findViewById(R.id.tvGameType1);
        tvGameType2 = findViewById(R.id.tvGameType2);
        tvGameType3 = findViewById(R.id.tvGameType3);
        tvGameInfo2 = findViewById(R.id.tv_game_info2);
        tvGameInfo3 = findViewById(R.id.tv_game_info3);
        //    @Bind(R.id.tv_game_info3)
//    TextView tvGameInfo3;
        tvGameScore = findViewById(R.id.tv_game_score);
        rbGameScore = findViewById(R.id.rb_game_score);
        tvDownCount = findViewById(R.id.tv_down_count);
        btnOpration = findViewById(R.id.btn_opration);


        rbCommentScroe = findViewById(R.id.rb_comment_scroe);
        tvGoComment = findViewById(R.id.tv_gocomment);

        btnComment = findViewById(R.id.btn_comment);

        tvEditorRecommend = findViewById(R.id.tv_editor_recommend);//小编的 简介

        cwvContentWebview = findViewById(R.id.cwv_content_webview);//简介的webview

        tvExpends = findViewById(R.id.tv_expends);
        //游戏的相关攻略
        elvAboutStrategy = findViewById(R.id.elv_about_strategy);

        llAboutGameContainer = findViewById(R.id.ll_about_game_container);//相关游戏.


        lRelatedContainer = findViewById(R.id.ll_relatedgame_container);//相关游戏的容器

        llVideoContentContainer = findViewById(R.id.ll_videocontent_container);//viode内容简介的 部分


        llEditorContainer = findViewById(R.id.ll_editor_container);//小编推荐模块 部分

        editorName = findViewById(R.id.tv_editor_name);//编辑的名字

        llScroe = findViewById(R.id.ll_scroe);//评分模块

        infoContainer = findViewById(R.id.ll_info_container);
        playerContainer = findViewById(R.id.fl_paly_layout);

        editorName.setOnClickListener(this);
        btnComment.setOnClickListener(this);
        llScroe.setOnClickListener(this);
        tvExpends.setOnClickListener(this);

        jcVideoplayer.setmAutoDirection(false);
        cwvContentWebview.setBackgroundColor(0);
    }

    /**
     * 设置 游戏的 详情内容
     */
    public void setGameContentData(GameContent mGameContent) {
        this.mGameContent = mGameContent;
        ImageLoadUtils.loadCornersImage(mGameContent.getAppIcon(), ivAppIcon, 10, R.drawable.game_icon_defpic);
        //游戏的简介模块 webview
        if (TextUtils.isEmpty(mGameContent.getVideoContent())) {
            llVideoContentContainer.setVisibility(View.GONE);
        } else {
            llVideoContentContainer.setVisibility(View.VISIBLE);
            //替换图片
            String content = cwvContentWebview.replaceImg(mGameContent.getVideoContent());
            cwvContentWebview.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
        }

        tvGameName.setText(mGameContent.getAppName());
        if (TextUtils.isEmpty(mGameContent.getSourceType())) {
            tvGameInfo1.setVisibility(View.GONE);
        } else {
//            tvGameInfo1.setVisibility(View.VISIBLE);
            tvGameInfo1.setText(mGameContent.getSourceType());
        }

        String appType = mGameContent.getAppType();
        if (!com.blankj.utilcode.util.StringUtils.isEmpty(appType)) {
            String[] split = appType.split(",");
            int length = split.length;
            if (length > 0) {
                tvGameType1.setText(split[0]);
                tvGameType1.setVisibility(View.VISIBLE);
            }
            if (length > 1) {
                tvGameType2.setText(split[1]);
                tvGameType2.setVisibility(View.VISIBLE);
            }
            if (length > 2) {
                tvGameType3.setText(split[2]);
                tvGameType3.setVisibility(View.VISIBLE);
            }
        }

        tvGameInfo3.setText(mGameContent.getGameType());

        tvGameInfo2.setText(mGameContent.getAppSize());

        editorName.setText(mGameContent.getSourceDesc());

        rbGameScore.setStar(StringUtils.toFloat(mGameContent.getGradeScore(), 0.0f) / 2);
        tvGameScore.setText(TextUtils.isEmpty(mGameContent.getGradeScore()) ? "0.0  " : mGameContent.getGradeScore() + "  ");
        tvDownCount.setText(TextUtils.isEmpty(mGameContent.getPerStartNum()) ? "0次" : mGameContent.getPerStartNum() + "次");


        rbCommentScroe.setStar(StringUtils.toFloat(mGameContent.getLatestStar(), 0.0f));


        //编辑的模块
//        mGameContent.setEditRecommend("第三方及第三方几点睡觉覅的数据覅及覅三级风景都搜附近的搜我金佛我就度搜你放假");
        if (TextUtils.isEmpty(mGameContent.getEditRecommend())) {
            llEditorContainer.setVisibility(View.GONE);
        } else {
            llEditorContainer.setVisibility(View.VISIBLE);
            tvEditorRecommend.setText(mGameContent.getEditRecommend());

        }

//        btnOpration.setText(AppApplication.getInstance().getString(R.string.game_down));
        tvGoComment.setText(AppApplication.getInstance().getString(R.string.game_go_comment));


        btnOpration.setTag(mGameContent);
        btnOpration.setTag(R.id.tag_four, "游戏详情");

    }


    /**
     * 设置相关游戏攻略
     */

    public void setAboutStretegyData(final List<GameRaidersEntity> strategyList) {
        if (strategyList == null || strategyList.isEmpty()) {
            ll_about_strategy.setVisibility(View.GONE);
        } else {
            ll_about_strategy.setVisibility(View.VISIBLE);
            elvAboutStrategy.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mGameContent.getShowStrategyMore()) {//是否显示查看更多攻略
                        View btnGotoMore = LayoutInflater.from(context).inflate(R.layout.layout_textbtn_footer, null);
                        btnGotoMore.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (mGameContent == null || activity == null) {
                                    return;
                                }
                                Intent intent = new Intent(activity, GameRaidersListActivity.class);
                                intent.putExtra(Config.Extra.PARAMETER1, mGameContent.getArticleId());
                                activity.startActivity(intent);
                            }
                        });
                        elvAboutStrategy.addFooterView(btnGotoMore);
                    }

                    GameRaidersAdapter adapter = new GameRaidersAdapter(strategyList, activity);
//                    btnGotoMore.setOnClickListener(onClick);

                    elvAboutStrategy.setAdapter(adapter);
                    elvAboutStrategy.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            if (strategyList == null || activity == null) {
                                return;
                            }
                            //防止越界
                            if (position >= strategyList.size()) {
                                position = strategyList.size() - 1;
                            } else if (position < 0) {
                                position = 0;
                            }
                            GameRaidersEntity newsEntity = strategyList.get(position);
                            if (newsEntity == null) {
                                return;
                            }
                            Intent intent = new Intent();
                            intent.putExtra(Config.Extra.PARAMETER1, newsEntity.getArticleId());
                            intent.putExtra(Config.Extra.PARAMETER2, newsEntity.getGameId());
                            if (TextUtils.equals(newsEntity.getArticleType(), TypeConstant.GAME_RAIDERS_TEXT)) {
                                intent.setClass(activity, GameRaidersNewsActivity.class);
                            } else if (TextUtils.equals(newsEntity.getArticleType(), TypeConstant.GAME_RAIDERS_VIDEO)) {
                                intent.setClass(activity, GameRaidersVideoActivity.class);
                            }
                            activity.startActivity(intent);
                        }
                    });
                }
            }, 0);
        }
    }


    /**
     * 悬挂titl 的高度
     *
     * @return
     */
    public int getStickyTop() {
        if (infoContainer != null && playerContainer != null) {
            int height = infoContainer.getHeight();
            int height1 = playerContainer.getHeight();
            return height + height1;
        }
        return 0;
    }


    public int getVideoTinyTop() {
        if (playerContainer != null) {
            int height1 = playerContainer.getHeight();
            return height1;
        }
        return 0;
    }


    /**
     * 相关游戏
     *
     * @param list
     */
    public void setAboutGameList(List<GameRelated> list) {
        if (llAboutGameContainer == null || lRelatedContainer == null) return;
        if (list == null || list.isEmpty()) {
            lRelatedContainer.setVisibility(View.GONE);
        } else {
            lRelatedContainer.setVisibility(View.VISIBLE);
            llAboutGameContainer.removeAllViews();
            for (int i = 0; i < list.size(); i++) {
                RelatedGameView relatedGameView = new RelatedGameView(context, list.get(i), i);
                relatedGameView.setOnClickListener(this);
                llAboutGameContainer.addView(relatedGameView);
            }

        }

    }


    /**
     * 更改游戏简介webview 的高度
     */
    private void changeWebViewContentHeight(boolean expends) {
        if (llVideoContentContainer != null && cwvContentWebview != null
                && cwvContentWebview.getVisibility() == View.VISIBLE
                && tvExpends != null) {
            ViewGroup.LayoutParams layoutParams = cwvContentWebview.getLayoutParams();
            if (!expends) {
                layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                cwvContentWebview.setLayoutParams(layoutParams);
                requestLayout();
                isExpended = true;
                tvExpends.setText(AppApplication.getInstance().getString(R.string.game_desc_show_up));
            } else {
                layoutParams.height = ViewSizeUtils.dp2px(AppApplication.getInstance(), 220);
                cwvContentWebview.setLayoutParams(layoutParams);
                requestLayout();
                isExpended = false;
                tvExpends.setText(AppApplication.getInstance().getString(R.string.game_desc_show_all));
            }
            try {
                GameDetailActivity activity = (GameDetailActivity) this.activity;
                if (activity != null && !activity.isFinishing() && activity.getDetailScrollView() != null) {
                    activity.getDetailScrollView().scrollToFirstView();

                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }

    }

    /**
     * 绑定activity
     *
     * @param activity
     */
    public void setActivity(Activity activity) {
        this.activity = activity;
    }


    /**
     * 刷新 分数和次数
     */
    public void flushScore() {
        if (rbCommentScroe != null && tvDownCount != null && mGameContent != null) {
            rbCommentScroe.setStar(StringUtils.toFloat(mGameContent.getLatestStar(), 0.0f));
            tvGameScore.setText(mGameContent.getGradeScore());
            rbGameScore.setStar(StringUtils.toFloat(mGameContent.getGradeScore(), 0.0f) / 2);
            tvDownCount.setText(mGameContent.getPerStartNum() + "次");

        }
//


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_comment://评分的
            case R.id.btn_comment_gone:
                if (activity != null && !activity.isFinishing() && mGameContent != null) {
                    Intent intent = new Intent(activity, GameCommentActivity.class);
                    intent.putExtra(Config.Extra.PARAMETER1, mGameContent.getArticleId());
                    activity.startActivity(intent);
                }
                break;
            case R.id.ll_scroe://评分详情
                if (activity != null && !activity.isFinishing() && mGameContent != null) {
                    Intent intent = new Intent(activity, GameScoreActivity.class);
                    intent.putExtra(Config.Extra.PARAMETER1, mGameContent.getArticleId());
                    intent.putExtra(Config.Extra.PARAMETER2, mGameContent.getArticleTitle());
                    intent.putExtra(IMAGE_URL, mGameContent.getPlotImg());
                    activity.startActivity(intent);
                }
                break;
            case R.id.tv_expends://查看webview的
                changeWebViewContentHeight(isExpended);
                break;
            case R.id.tv_editor_name:
                if (mGameContent != null) {
                    String sourceQQ = mGameContent.getSourceQQ();
                    if (!com.blankj.utilcode.util.StringUtils.isEmpty(sourceQQ)) {
                        ClipboardUtils.copyText(sourceQQ);
                        ToastUtils.showShort("已复制成功");
                    }
                }
                break;
            case R.id.relatedview://相关游戏
                try {
                    if (activity != null && !activity.isFinishing()) {
                        RelatedGameView tag = (RelatedGameView) v;
                        String gameId = (String) tag.getTag();
                        Intent intent = new Intent();
                        intent.putExtra(Config.Extra.PARAMETER1, gameId);
                        intent.setClass(activity, GameDetailActivity.class);
                        activity.startActivity(intent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;

        }
    }

    public interface OnViewScrollListener {
        void onViewScrolling(int l, int t, int oldl, int oldt);
    }


    public void setOnViewScrollListener(OnViewScrollListener mOnViewScrollListener) {

        this.mOnViewScrollListener = mOnViewScrollListener;
    }


    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (mOnViewScrollListener != null) {
            mOnViewScrollListener.onViewScrolling(l, t, oldl, oldt);
        }
    }


    /**
     * 内容滑动到最底端
     *
     * @return
     */
    public void scrollBottom() {
        fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
    }


    public void scrollTop() {
        fullScroll(ScrollView.FOCUS_UP);//滚动到底部
    }


    public float getWebviewY() {
        if (webviewY == 0 && cwvContentWebview != null) {
            webviewY = cwvContentWebview.getY();
        }

        return webviewY;
    }


    public void onDestory() {
//        ButterKnife.unbind(this);
    }


    public LinearLayout getContent() {
        return llVideoContentContainer;
    }


}
